package com.real8.romemp.client.activity;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.real8.romemp.client.ClientFactory;
import com.real8.romemp.client.GameConstants;
import com.real8.romemp.client.place.FeedPlace;
import com.real8.romemp.client.place.TradePlace;
import com.real8.romemp.client.ui.TradeView;
import com.real8.romemp.client.ui.TradeView.Presenter;
import com.real8.romemp.shared.GameData;

public class TradeActivity extends AbstractActivity implements Presenter {
	private final ClientFactory clientFactory;
	private TradeView view;

	public TradeActivity(TradePlace place, ClientFactory clientFactory) {
		this.clientFactory = clientFactory;
	}

	@Override
	public void start(AcceptsOneWidget containerWidget, EventBus eventBus) {
		view = clientFactory.getTradeView();
		if (view != null) {
			view.setPresenter(this);

			// prepare view
			view.hideAll();

			// determine profit
			final GameData gameData = clientFactory.getGameData();
			int tradeRate = gameData.getVL_tradeRate();
			int localProfit = gameData.getML_localMerchantShips() * tradeRate;
			int overseeProfit = gameData.getMO_overseeMerchantShips()
					* tradeRate * 20;
			gameData.setTR_treasury(gameData.getTR_treasury() + localProfit
					+ overseeProfit);

			// show profit
			view.showProfit(localProfit, overseeProfit, gameData
					.getTR_treasury());

			// delay a bit
			Timer timer = new Timer() {
				@Override
				public void run() {
					// determine expenses
					int auxilia = gameData.getMH_auxiliaHired();
					int auxiliaExpenses = auxilia * 2500;
					int army = gameData.getLA_labourArmy();
					int armyExpenses = army * 500;
					int marines = gameData.getLN_labourNavy();
					int navyExpenses = marines * 500;
					gameData.setTR_treasury(gameData.getTR_treasury()
							- auxiliaExpenses - armyExpenses - navyExpenses);

					// show expenses
					view.showExpenses(auxilia, auxiliaExpenses, army,
							armyExpenses, marines, navyExpenses);

					// show balance
					view.showBalance(gameData.getTR_treasury());

					// show continue
					view.showContinue();
				}
			};
			timer.schedule(GameConstants.DELAY_6020);

			// set widget
			containerWidget.setWidget(view.asWidget());
		}
	}

	@Override
	public void onContinue() {
		goToNextPlace();
	}

	private void goToNextPlace() {
		clientFactory.getPlaceController().goTo(new FeedPlace());
	}
}
